package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.common.util.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.SqlUtil;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends
        ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
         //获取手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        checkPhoneAndCodeIsEmpty(phone, code);
        // TODO 判断手机验证码和输入验证码是否一致
        if(code.equals("123123")){
            System.out.println("验证码正确");
        }

        //判断是否第一次登录 根据手机号查询数据库，如果不存在相同手机号就是第一次登录
        UserInfo userInfo = getUserInfoByPhone(phone);
        //判断user是否为null，为null就保存
        checkUserIsNull(phone, userInfo);
        //判断是否被禁用
        checkUserInfoStatus(userInfo);
        return getMapByUserInfo(userInfo);
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证信息
        setUserInfo(userAuthVo, userInfo);
        //进行信息更新
        baseMapper.updateById(userInfo);
    }

    //认证审批  2通过  -1不通过
    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //UserInfoQueryVo获取条件值
        String name = userInfoQueryVo.getKeyword(); //用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间
        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = getUserInfoQueryWrapper(name, status, authStatus, createTimeBegin, createTimeEnd);
        //调用mapper的方法
        IPage<UserInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().forEach(this::packageUserInfo);
        return pages;
    }

    @Override
    public void lock(Long userId, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            UserInfo userInfo = this.getById(userId);
            userInfo.setStatus(status);
            this.updateById(userInfo);
        }
    }

    //用户详情
    @Override
    public Map<String, Object> show(Long userId) {

        //根据userid查询用户信息 并包装
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllByUserId(userId);
        return getUserInfoAndParentListMap(userInfo, patientList);
    }

    private Map<String, Object> getUserInfoAndParentListMap(UserInfo userInfo, List<Patient> patientList) {
        Map<String,Object> map = new HashMap<>();
        map.put("userInfo", userInfo);
        map.put("patientList", patientList);
        return map;
    }

    private QueryWrapper<UserInfo> getUserInfoQueryWrapper(String name, Integer status, Integer authStatus, String createTimeBegin, String createTimeEnd) {
        QueryWrapper<UserInfo> wrapper = new SqlUtil.Dynamic<UserInfo>()
                .like("name", name)
                .eq("status", status)
                .eq("auth_status", authStatus)
                .ge("create_time", createTimeBegin)
                .le("create_time", createTimeEnd)
                .build();
        return wrapper;
    }

    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }

    private void setUserInfo(UserAuthVo userAuthVo, UserInfo userInfo) {
        //认证人姓名
        //userInfo.setName(userAuthVo.getName());
        //其他认证信息
        BeanUtils.copyProperties(userAuthVo,userInfo);
        //userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        //userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        //userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
    }

    private void checkUserIsNull(String phone, UserInfo userInfo) {
        if(userInfo == null){
            saveUser(phone);
        }
    }

    private Map<String, Object> getMapByUserInfo(UserInfo userInfo) {
        Map<String,Object> map = new HashMap<>();
        //token生成
        String token = JwtHelper.createToken(userInfo.getId(), userInfo.getName());
        map.put("name", userInfo.getName());
        map.put("token",token);
        return map;
    }

    private void checkUserInfoStatus(UserInfo userInfo) {
        if(userInfo.getStatus() == 0){
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
    }

    private UserInfo getUserInfoByPhone(String phone) {
        QueryWrapper<UserInfo> wrapper =  new QueryWrapper<>();
        wrapper.eq("phone", phone);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        return userInfo;
    }

    private void saveUser(String phone) {
        //第一次使用该手机号登录 添加到数据库
        UserInfo userInfo = new UserInfo();
        userInfo.setStatus(1);
        userInfo.setPhone(phone);
        userInfo.setName("test");
        baseMapper.insert(userInfo);
    }

    private void checkPhoneAndCodeIsEmpty(String phone, String code) {
        if(StringUtils.isEmpty(code) || StringUtils.isEmpty(phone)){
            throw  new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
    }
}